package io.renren.common.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Objects;
import java.util.Properties;

/**
 * @auther xiegaolong
 * @description
 * @date 2024/12/2
 */
@Slf4j
public class PropertiesUtils {

    //spring.profiles.active 是哪个激活的配置文件
    private static String active;

    //静态代码块,自动获取用户配置的配置文件
    static {
        active = (String) getValue("spring.profiles.active");
        if (active == null || "".equals(active)) {
            active = "";
        }
    }


    /**
     * 根据传入的yml获取yml中key的属性值
     *
     * @param key
     * @param yml
     * @return
     */
    private static Object getValue(String key, String yml) {
        Resource resource = new ClassPathResource(yml);
        Properties properties;
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties = yamlFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        if (Objects.nonNull(properties)){
            return properties.get(key);
        }
        return null;
    }

    /**
     * 自动根据 application中激活的配置文件,选择对应的yml读取属性
     * @param key
     * @return
     */
    private static Object getValue(String key) {
        Object value = getValue(key, "application.yml");
        if (value != null) {
            return value;
        }
        if (!active.contains("application")) {
            active = "application-" + active + ".yml";
        }
        return getValue(key, active);
    }

    public static String getString(String key) {
        Object value = getValue(key);
        return (String)value;
    }

    public static int getInt(String key) {
        Object value = getValue(key);
        return (Integer) value;
    }

    public static boolean getBoolean(String key){
        Object value = getValue(key);
        return (Boolean)value;
    }

    public static Long getLong(String key) {
        Object value = getValue(key);
        return (Long) value;
    }

}
